<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/3/7
 * Time: 17:42
 * Desc: 我的购物车
 */
namespace app\index\service;
use think\Controller;
use think\Db;
use app\comm\service\DadaOpenapi;

class MycartService extends Controller{
    /**
     * @Author  lingyun
     * @Desc    获取头部信息
     */
    public function get_header(){
        $sql = "SELECT id,name,logo,cat_id FROM ys_goods AS a WHERE 6> (SELECT COUNT(*) FROM ys_goods WHERE cat_id=a.cat_id AND id>a.id) AND a.is_online=1 AND a.status=1 AND a.is_deleted=0 AND is_top>0 ORDER BY a.id DESC";
        $tui_goods = Db::query($sql);
        $category = get_top_category();           //商品顶级分类
        $exp_category = get_exp_category();       //商品扩展分类

        $this->assign('tui_goods',$tui_goods);
        $this->assign('category',$category);
        $this->assign('exp_category',$exp_category);

    }

    /**
     * @Author  lingyun
     * @Desc    搭配商品
     * 2018-04-27
     */
    public function get_dapei_goods(){
        $where_goods_arr = [
            'a.store_id'=>0,
            'a.is_deleted'=>0,
            'a.is_online'=>1,       //恢复线上线下状态 @lingyun  2018-03-29
            'a.status'=>1,
//            'a.cat_id'=>$cate_id,
//            'a.exp_cat'=>$exp_cate
        ];
        $join = [
            ['ys_sys_level b','a.member_level_id=b.id','LEFT']
        ];
        $goods = db('goods')->alias('a')->join($join)->field('a.*,b.title,b.css_color')->where($where_goods_arr)->limit(8)->order('id desc')->select();

        $this->assign('dp_goods',$goods);
    }

    /**
     * @Author  lingyun
     * @Desc    我的购物车
     * 2018-03-29
     */
    public function my_cart(){
        $store_id = cookie('store_id');
        $member = db('user')->where('uid',session('_user_uid_.uid'))->field('uid,realname,nickname,level_id')->find();      //会员信息

        if(empty($store_id)){
            $this->error('请选择城市',url('Changestore/index'));
        }
        $my_cart = (array)cookie('user_cart');     //会员的购物车
        $my_cart = $this->filter_cart_data($my_cart);
        $specid = array_column($my_cart,'specid');        //属性id

        $where = [
            'a.id'=>['in',$specid],
            'a.is_deleted'=>['eq',0],
            'b.status'=>['eq',1],
            'b.is_deleted'=>['eq',0],
            'c.store_id'=>$store_id,
            'c.is_deleted'=>0,
            'c.onsale'=>1
        ];

        //商品数据
        $goods = db('goods_spec_detail')->alias('a')->join('ys_store_goods_stock c','a.id=c.goods_spec_id','LEFT')->join('ys_goods b','a.goods_id=b.id','LEFT')->where($where)->field('a.id as spec_id,a.title,a.price,a.member_price,b.member_level_id,c.stock,b.name,b.logo,b.id as goods_id')->select();

        $total_num = 0;
        $total_amount = 0;
        //组合商品属性
        foreach($goods as $k=>$v){
            foreach($my_cart as $k1=>$v1){
                if($v1['specid'] == $v['spec_id']){
                    if($v1['goods_sum'] > $v['stock']){
                        if($v['stock'] == 0){
                            $goods[$k]['num'] = 0;
                        }else{
                            $goods[$k]['num'] = $v['stock'];
                        }
                    }else{
                        $goods[$k]['num'] = $v1['goods_sum'];
                    }
                    if($v['member_level_id'] != 1 && $member['level_id'] >= $v['member_level_id']){
                        $goods[$k]['total_price'] = $v1['goods_sum']*$v['member_price'];        //使用会员价
                        $goods[$k]['is_member'] = 1;                                            //是会员
                    }else{
                        $goods[$k]['total_price'] = $v1['goods_sum']*$v['price'];               //使用原始价
                        $goods[$k]['is_member'] = 0;                                            //是会员
                    }
                }
            }
            if($goods[$k]['num'] == 0){
                unset($goods[$k]);
                continue;
            }
            $total_num += $goods[$k]['num'];
            $total_amount += $goods[$k]['total_price'];
        }
//halt($goods);
        $this->assign('goods',$goods);                  //购物车商品
        $this->assign('member',$member);                //会员信息
        $this->assign('total_num',$total_num);          //商品总数
        $this->assign('total_amount',$total_amount);    //商品总价
        $this->assign('url',url('MyCart/my_cart'));                     //登录，选择门店的回调url
    }

    /**
     * @Author  lingyun
     * @Desc    过滤购物车的数据，选出当前门店下的购物车的商品
     * @param $data
     * @return bool
     * 2018-03-30
     */
    public function filter_cart_data($data){
        $store_id = cookie('store_id');
        foreach($data as $k=>$v){
            if($v['store_id'] != $store_id){
                unset($data[$k]);
            }
        }
        return $data;
    }

    /**
     * @Author  lingyun
     * @Desc    减少购物车商品
     * 2018-03-30
     */
    public function reduce_cart(){
        $post = input('post.');
        $store_id = cookie('store_id');

        $stock = db('store_goods_stock')->where(['store_id'=>$store_id,'goods_spec_id'=>$post['id'],'is_deleted'=>0,'onsale'=>1])->value('stock');
        $user_cart = $this->filter_cart_data(cookie('user_cart'));     //获取等前门店的购物车信息
        $catid = $post['id'];
        //数组主键索引
        $k = implode('',array_keys(array_filter($user_cart, function($t) use ($catid) { return $t['specid'] == $catid; })));
        $user_cart = cookie('user_cart');

        if($stock === null){                //该商品已经下架，将清空购物车内商品信息
            unset($user_cart[$k]);
            cookie('user_cart',$user_cart,15552000);
            return ['code'=>-1,'msg'=>'该商品已经下架，将从购物车中移除该商品'];
        }else if($user_cart[$k]['goods_sum'] == 1){             //删除购物车的商品
            unset($user_cart[$k]);
            cookie('user_cart',$user_cart,15552000);
            return ['code'=>1,'msg'=>'成功删除该购物车商品'];
        }else if($user_cart[$k]['goods_sum'] >= $stock+2){      //商品库存不足，自动恢复至商品最大库存
            $user_cart[$k]['goods_sum'] = $stock;               //恢复至商品的最大库存
            cookie('user_cart',$user_cart,15552000);
            return ['code'=>0,'msg'=>'购物车的商品数量超出商品的库存，自动恢复至商品的最大库存数量','goods_sum'=>$stock];
        }

        $user_cart[$k]['goods_sum'] = $user_cart[$k]['goods_sum']-1;

        cookie('user_cart',$user_cart,15552000);
        return ['code'=>1,'msg'=>'减少成功'];
    }

    /**
     * @Author  lingyun
     * @Desc    增加购物车数量
     * 2018-03-30
     */
    public function increase_cart(){
        $post = input('post.');                 //goods_spec_detail -> id
        $store_id = cookie('store_id');
        $stock = db('store_goods_stock')->where(['store_id'=>$store_id,'goods_spec_id'=>$post['id'],'is_deleted'=>0,'onsale'=>1])->value('stock');

        $user_cart = $this->filter_cart_data(cookie('user_cart'));     //获取等前门店的购物车信息
        $catid = $post['id'];
        $cart = array_filter($user_cart, function($t) use ($catid) { return $t['specid'] == $catid; });
        $k = implode('',array_keys($cart));         //购物车的主键id

        $user_cart = cookie('user_cart');           //会员的购物车全部商品信息

        if($stock === null){            //商品已经下架，删除购物车的该商品信息
            unset($user_cart[$k]);
            cookie('user_cart',$user_cart,15552000);
            return ['code'=>-1,'msg'=>'该商品已经下架，将从购物车中移除该商品'];
        }else if($cart[$k]['goods_sum']>=$stock){
            return ['code'=>0,'msg'=>'商品库存不足，无法继续添加'];
        }

        $user_cart[$k]['goods_sum'] = $user_cart[$k]['goods_sum']+1;
        cookie('user_cart',$user_cart,15552000);
        return ['code'=>1,'msg'=>'增加成功'];
    }

    /**
     * @Author  lingyun
     * @Desc    删除购物车的商品
     * 2018-03-30
     */
    public function del(){
        $post = input('post.');
        $store_id = cookie('store_id');
        $user_cart = $this->filter_cart_data(cookie('user_cart'));     //获取等前门店的购物车信息
        $catid = $post['id'];
        //数组主键索引
        $k = implode('',array_keys(array_filter($user_cart, function($t) use ($catid) { return $t['specid'] == $catid; })));
        $user_cart = cookie('user_cart');
        unset($user_cart[$k]);
        cookie('user_cart',$user_cart,15552000);                       //商品购物车信息
        $this->success('删除成功','');
    }

    /**
     * @Author  lingyun
     * @Desc    清空购物车
     * 2018-03-30
     */
    public function qingkong(){
        $store_id = cookie('store_id');
        $cur_cart = $this->filter_cart_data(cookie('user_cart'));     //获取当前门店的购物车信息
        $user_cart = cookie('user_cart');       //会员购物车信息
        foreach($cur_cart as $k=>$v){
            unset($user_cart[$k]);
        }
        cookie('user_cart',$user_cart,15552000);                       //商品购物车信息
        $this->success('清空成功','');
    }

    /**
     * @Author  lingyun
     * @Desc    提交订单前进行购物车检查
     * 2018-04-28
     */
    public function check_cart(){
        $post = input('post.');     //68,71，
        $uid = session('_user_uid_.uid');           //判断会员是否已经登录
        if(empty($uid)){
            $this->error(-1,'');
        }

        $ids = trim($post['ids'],',');
        $store_id = cookie('store_id');
        $user_cart = $this->filter_cart_data(cookie('user_cart'));      //当前门店的购物车

        $spec_arr = explode(',',$ids);
        foreach($user_cart as $k => $v){
            if(!in_array($v['specid'],$spec_arr)){
                unset($user_cart[$k]);
            }
        }
        $where = [
            'a.store_id'=>$store_id,
            'a.goods_spec_id'=>['in',$ids]
        ];
        $goods = db('store_goods_stock')->alias('a')->join('ys_goods_spec_detail b','a.goods_spec_id=b.id','LEFT')->join('ys_goods c','a.goods_id=c.id','LEFT')->where($where)->field('a.*,b.title,b.is_deleted as deleted_one,c.name,c.status as g_status,c.is_deleted as g_is_deleted')->select();      //门店商品信息
        foreach($goods as $k=>$v){     //判断商品是否出售、库存是否充足
            foreach($user_cart as $k1=>$v1){
                if($v['goods_spec_id'] == $v1['specid']){
                    if($v['onsale'] == 0 || $v['is_deleted'] == 1 || $v['g_status'] == 0 || $v['g_is_deleted'] == 1 || $v['deleted_one'] == 1){
                        $cart = cookie('user_cart');
                        unset($cart[$k1]);      //删除购物车元素
                        cookie('user_cart',$cart,15552000);        //更新购物车数据
                        $this->error($v['name'].' '.$v['title'].'已经下架，将从购物车中删除该商品','');
                    }
                    if($v['stock']<$v1['goods_sum']){
                        $this->error($v['name'].' '.$v['title'].'商品库存不足，您最多可以购买'.$v['stock'].'个商品','');
                    }
                }
            }
        }
        $this->success('成功','');
    }

    /**
     * @Author  lingyun
     * @Desc    提交订单
     */
    public function pre_create_order(){
        $post = input('post.');

//        $ids = implode(',',$post['ids']);
        $ids = $post['ids'];
//        $ids = explode(',',trim($post['ids'],','));       //68.69

        $store_id = cookie('store_id');
        $uid = session('_user_uid_.uid');         //当前登录的会员id
        $cart = cookie('user_cart');            //购物车所有信息
        $user_cart = $this->filter_cart_data(cookie('user_cart'));     //获取当前门店的购物车信息
        //获取选中的购物车列表
        foreach($user_cart as $k=>$v){
            if(!in_array($v['specid'],$ids)){
                unset($user_cart[$k]);
            }
        }
        if(empty($store_id)){       //选择门店
            $this->assign('err_msg','请先选择门店');
            $this->assign('err_url',url('Index/index'));
            $this->assign('err_button','选择门店');
            return false;
        }
        if($uid == ''){        //去登录
            $this->assign('err_msg','您目前还没有登录，请先去登录');
            $this->assign('err_url',url('Login/loginin'));
            $this->assign('err_button','登录');
            return false;
        }
        $member = db('user')->where('uid',$uid)->field('uid,user_money,openid,realname,level_id')->find();        //会员信息
        $where = [
            'a.store_id'=>$store_id,
            'a.goods_spec_id'=>['in',$ids]
        ];
        $goods = db('store_goods_stock')->alias('a')->join('ys_goods_spec_detail b','a.goods_spec_id=b.id','LEFT')->join('ys_goods c','a.goods_id=c.id','LEFT')->where($where)->field('c.id,c.logo,c.name,c.cat_id,c.unit,b.price,b.member_price,b.title,a.stock,a.id,a.is_deleted,a.onsale,a.goods_spec_id,c.member_level_id,a.spec_title')->select();

//        //购物车的商品
//        $goods = db('order_cart')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('ys_goods_spec_detail c','a.specid=c.id','LEFT')->join('ys_store_goods_stock d','a.store_goods_stock_id=d.id','LEFT')->where('a.id','in',$ids)->field('a.*,b.logo,b.name,b.cat_id,b.unit,c.price,c.title,d.stock,d.is_deleted,d.onsale,(a.goods_sum*c.price) as all_amount')->select();

        $total_amount = 0;      //订单总价
        $delivery_fee = 0;      //计算运费
        $address_id = 0;        //默认地址id
        $coupon_cat_id = '';    //优惠券的商品分类id，用于选择优惠券或者代金券
        //循环检测商品是否库存充足、是否上线出售
        foreach($goods as $k => $v){
            if($v['is_deleted'] == 1 || $v['onsale'] == 0){
//                $this->assign('err_msg',$v['name']." -- ".$v['title']."已经下架，请重新选择");
                $this->assign('err_msg',"商品已下架，请重新选择");
                $this->assign('err_url',url('MyCart/my_cart'));
                $this->assign('err_button','重新购买');
                foreach($cart as $k1 => $v1){
                    if($v1['store_id'] == $store_id && $v1['specid'] == $v['goods_spec_id']){
                        unset($cart[$k1]);
                    }
                }
                cookie('user_cart',$cart,15552000);                       //商品购物车信息
                return false;
            }
            foreach($user_cart as $k1=>$v1){
                if($v['goods_spec_id'] == $v1['specid']){
                    if($v['stock'] < $v1['goods_sum']){
                        unset($cart[$k1]);
                        cookie('user_cart',$cart,15552000);     //更新购物车
                        $this->assign('err_msg',$v['name']."：".$v['title']."库存不足，请选择其它商品");
                        $this->assign('err_url',url('MyCart/my_cart'));
                        $this->assign('err_button','重新购买');
                        return false;
                    }else{
                        $goods[$k]['goods_sum'] = $v1['goods_sum'];
                        if($member['level_id'] >= $v['member_level_id']){       //会员价格支付
                            $goods[$k]['all_amount'] = $v['member_price']*$goods[$k]['goods_sum'];
                            $goods[$k]['goods_price'] = $v['member_price'];
                            $total_amount += $v1['goods_sum']*$v['member_price'];       //商品总价
                        }else{              //普通价格支付
                            $goods[$k]['all_amount'] = $v['price']*$goods[$k]['goods_sum'];
                            $goods[$k]['goods_price'] = $v['price'];
                            $total_amount += $v1['goods_sum']*$v['price'];       //商品总价
                        }

                        $coupon_cat_id .= $v['cat_id'].",";
                    }
                }
            }
        }

        //分类去重，并且用逗号隔开组成字符串
        $coupon_cat_id = implode(',',array_unique(explode(',',rtrim($coupon_cat_id,','))));
//        halt($coupon_cat_id);
        //默认收货地址,计算默认地址的运费
        $address = db('user_address')->where(['uid'=>$uid,'is_default'=>1])->find();
        if(!empty($address)){
            $result = $this->count_delivery_fee($address['address']);
            if($result['code'] == 0){
                $delivery_fee = 0;
                $address_id  = 0;
            }else{
                $delivery_fee = $result['msg'];
                $address_id = $address['id'];
            }
        }
        $final_amount = $delivery_fee+$total_amount;        //最终支付金额

        $sql = "SELECT id,name,logo,cat_id FROM ys_goods AS a WHERE 5> (SELECT COUNT(*) FROM ys_goods WHERE cat_id=a.cat_id AND id>a.id) AND a.is_online=1 ORDER BY a.id DESC";
        $tui_goods = Db::query($sql);
        $coupon = $this->get_coupon_list($final_amount,$coupon_cat_id);      //优惠券列表
        $cash_coupon = $this->get_cash_coupon($coupon_cat_id);                //代金券列表
        $address_list = db('user_address')->where(['uid'=>$uid,'deleted'=>0])->select();        //全部地址列表
        $category = get_top_category();           //商品顶级分类
        $exp_category = get_exp_category();       //商品扩展分类
        if(isMobile()){
            if(is_weixin()){
                $this->assign('is_mobile',0);
            }else{
                $this->assign('is_mobile',1);
            }
        }else{
            $this->assign('is_mobile',1);
        }

        $cur_city = db('city')->where('key',cookie('city_key'))->value('value');        //当前城市
        $city_list = db('city')->where(['status'=>1,'is_deleted'=>0])->select();


        $this->assign('cur_city',$cur_city);                //当前城市
        $this->assign('url',request()->url(true));
        $this->assign('city',$city_list);                   //城市列表
        $this->assign('tui_goods',$tui_goods);              //顶部推荐商品
        $this->assign('address',$address_list);             //收货地址列表
        $this->assign('default_address',$address);          //默认收货地址
        $this->assign('address_id',$address_id);            //默认收货地址
        $this->assign('category',$category);                //商品分类
        $this->assign('exp_category',$exp_category);        //商品扩展分类
        $this->assign('goods',$goods);                      //商品
//        $this->assign('num',$post['num']);                //购买数量
        $this->assign('total_amount',$total_amount);        //订单总价
        $this->assign('address_id',$address_id);            //默认收货地址
        $this->assign('delivery_fee',$delivery_fee);        //运费
        $this->assign('final_amount',$final_amount);        //运费
        $this->assign('coupon_cat_id',$coupon_cat_id);      //运费
        $this->assign('member',$member);                    //余额
        $this->assign('nowtime',date('Y-m-d',time()));
        $this->assign('num',count($goods));                 //商品数量
        $this->assign('order_sn',create_order_sn($uid));    //订单编号
        $this->assign('coupon',$coupon);                    //优惠券
        $this->assign('cash_coupon',$cash_coupon);          //代金券
        $this->assign('count_coupon',count($coupon));          //代金券
        $this->assign('count_cash_coupon',count($cash_coupon));          //代金券
        $this->assign('ids',$ids);                          //购物车商品ID，用‘，’隔开
        $this->assign('member',$member);                    //购物车商品ID，用‘，’隔开
        $this->assign('ids',implode(',',$ids));                    //购物车商品ID，用‘，’隔开
        return true;
    }




    /**
     * @Author  lingyun
     * @Desc    检查订单的正确性
     * @Param   $param  提交的信息
     * 2018-04-28
     */
    public function check_pay_order($param){
        $uid = session('_user_uid_.uid');
        $member = db('user')->where('uid',session('_user_uid_.uid'))->field('uid,user_money,level_id')->find();           //会员信息
        $order_sn = create_order_sn($uid);      //订单编号
        $address = db('user_address')->where('id',$param['address_id'])->find();     //收货地址

        $user_cart = $this->filter_cart_data(cookie('user_cart'));     //获取等前门店的购物车信息
        $cart = cookie('user_cart');            //会员购物车信息
        $spec_id = explode(',',$param['ids']);            //购物车
//        halt($spec_id);        //3,80
//        halt($user_cart);      //1,80,3
        foreach($user_cart as $k=>$v){
            if(!in_array($v['specid'],$spec_id)){
                unset($user_cart[$k]);     //删除会员购物车
                continue;
            }
            unset($cart[$k]);
//            cookie('user_cart',$cart,15552000);     //更新购物车信息
        }

        $where_goods = [
            'a.id'=>['in',$spec_id],
            'b.store_id'=>['eq',cookie('store_id')],
        ];
        $goods = db('goods_spec_detail')->alias('a')->join('ys_store_goods_stock b','a.id=b.goods_spec_id','LEFT')->join('ys_goods c','a.goods_id=c.id','LEFT')->where($where_goods)->field('a.*,a.id as specid,b.id as store_goods_stock_id,b.stock,b.onsale,b.is_deleted as deleted_one,c.member_level_id')->select();
//        //购物车商品信息
//        $goods = db('order_cart')->alias('a')->join('ys_goods_spec_detail b','a.specid=b.id','LEFT')->where('a.id','in',$post['ids'])->field('a.*,b.title,b.price')->select();
        //就按商品总价格
        $total_amount = 0;      //商品总价
        $goods_num = 0;         //商品数量

        foreach($goods as $k => $v){
            foreach($user_cart as $k1=>$v1){
                if($v['id'] == $v1['specid']){
                    if($v['member_level_id'] != 1 && $member['level_id'] >= $v['member_level_id']){        //使用会员价格
                        $total_amount+=$v1['goods_sum']*$v['member_price'];     //会员价格
                        $goods[$k]['price'] = $v['member_price'];
                    }else{
                        $total_amount+=$v1['goods_sum']*$v['price'];     //普通会员价格
                    }
                    $goods_num+=$v1['goods_sum'];
                    $goods[$k]['goods_sum'] = $v1['goods_sum'];
                }
            }
        }
//halt($goods);
        //商品运费
        if($param['is_ziqu'] == 0){
            $result = $this->count_delivery_fee($address['address']);

//        halt($result);
            if($result['code'] == 0){
                return ['code'=>0,'err_msg'=>'收货地址有误，请重新选择','err_url'=>url('MyCart/my_cart'),'err_button'=>'重新下单'];
            }
            $shipping_price = $result['msg'];       //商品运费
        }else{
            $shipping_price = 0;       //商品运费
        }

        if(!empty($param['coupon_id'])){
            $coupon = db('user_ycard')->where('id',$param['coupon_id'])->find();
            if($coupon['user_start_time']<time() && $coupon['use_end_time']>time() && $coupon['is_used'] == 0){
                $coupon_price = $coupon['reduce'];
                $param['coupon_price'] = $coupon_price;
            }else{
                $param['coupon_id'] - 0;
                $coupon_price = 0;
                $param['coupon_price'] = 0;
            }
        }else{
            $coupon_price = 0;
            $param['coupon_id'] - 0;
            $param['coupon_price'] = 0;
        }

        if(!empty($param['cash_coupon_id'])){
            $cash_coupon = db('user_ycard')->where('id',$param['cash_coupon_id'])->find();
            if($cash_coupon['use_start_time']<time() && $cash_coupon['use_end_time']>time() && $cash_coupon['is_used'] == 0){
                $cash_coupon_price = $cash_coupon['value'];
                $param['cash_coupon_price'] = $cash_coupon_price;
            }else{
                $cash_coupon_price = 0;
                $param['cash_coupon_id'] = 0;
                $param['cash_coupon_price'] = 0;
            }
        }else{
            $cash_coupon_price = 0;
            $param['cash_coupon_id'] = 0;
            $param['cash_coupon_price'] = 0;
        }

        $final_amount = $total_amount+$shipping_price-$coupon_price-$cash_coupon_price;      //最终成交价格

        if($param['is_ziqu'] == 1){         //自取订单
            $final_amount = $final_amount-$shipping_price;
            $shipping_price = 0;
        }

        //ys_order 的入库数据
        $order_data_arr = [
            'uid'=>$uid,
            'coupon_id'=>$param['coupon_id'],
            'coupon_price'=>$coupon_price,
            'cash_coupon_id'=>$param['cash_coupon_id'],
            'cash_coupon_price'=>$cash_coupon_price,
            'order_type'=>1,
            'order_sn'=>$order_sn,
            'store_id'=>cookie('store_id'),
            'order_status'=>0,
            'shipping_status'=>0,
            'delivery_time'=>'',
            'consignee'=>$address['consignee'],
            'country'=>$address['country'],
            'province'=>$address['province'],
            'city'=>$address['city'],
            'district'=>$address['area'],
            'twon'=>$address['twon'],
            'address'=>$address['address'],
            'zipcode'=>$address['zipcode'],
            'mobile'=>$address['mobile'],
            'email'=>$address['email'],
            'receiver_lng'=>$address['lng'],        //收货人经度
            'receiver_lat'=>$address['lat'],        //收货人纬度
            'pay_type'=>$param['pay_type'],
            'pay_status'=>0,                        //未支付
            'goods_num'=>$goods_num,                //商品数量
            'goods_price'=>$total_amount,           //商品总价
            'shipping_price'=>$shipping_price,      //商品运费
            'order_amount'=>$final_amount,          //商品应付金额
            'final_amount'=>$final_amount,          //商品最终支付价
            'addtime'=>time(),
            'user_note'=>$param['user_note'],
            'score'=>floor($final_amount/3),
            'is_deleted'=>0,
            'address_id'=>$param['address_id'],      //门店id
            'is_ziqu'=>$param['is_ziqu'],      //门店id
        ];
        $order_id = db('order')->insertGetId($order_data_arr);       //订单信息入库

        foreach($goods as $k => $v){
            //订单详情入库数据
            $order_detail_data_arr = [
                'uid'=>$uid,
                'order_id'=>$order_id,
                'spec_id'=>$v['specid'],
                'spec_detail'=>$v['title'],
                'goods_id'=>$v['goods_id'],
                'goods_num'=>$v['goods_sum'],
                'spec_price'=>$v['price'],
                'discount_signal_price'=>$v['price']-($order_data_arr['coupon_price']+$order_data_arr['cash_coupon_price'])/$goods_num,          //平摊优惠券之后的单价
                'final_amount'=>($v['price']-($order_data_arr['coupon_price']+$order_data_arr['cash_coupon_price'])/$goods_num)*$v['goods_sum'],
                'status'=>0,
                'storeid'=>cookie('store_id'),
                'is_online'=>1,
                'addtime'=>time(),
                'store_goods_stock_id'=>$v['store_goods_stock_id']
            ];
            db('order_details')->data($order_detail_data_arr)->insert();
        }
        //订单动作记录入库状态
        $order_action_arr = [
            'uid'=>$uid,
            'order_id'=>$order_id,
            'action_user'=>0,
            'order_status'=>0,
            'pay_status'=>0,
            'status_desc'=>'订单待支付',
            'storeid'=>cookie('store_id'),
            'addtime'=>time()
        ];

        $res = db('order_action')->data($order_action_arr)->insert();           //订单动作详情记录

        //可领取的优惠券列表
        $time = time();
        $sql = "select a.*,ifnull(b.coupon_id,0) as is_received from ys_store_coupon as a left join (select coupon_id,store_id,uid from ys_user_ycard where uid=".$uid." and store_id=".cookie('store_id').") as b on a.id=b.coupon_id where a.store_id=".cookie('store_id')." and a.condition<=".$final_amount." and a.send_start_time<".$time." and a.send_end_time>".$time." and a.is_deleted=0 and a.type=0 and a.status=1 and a.create_num>a.send_num";
        $receive_coupon = Db::query($sql);
        $total = count($receive_coupon);
        $receive_coupon_id = '';         //可以领取的优惠券id
        foreach($receive_coupon as $k => $v){
            if($v['is_received']>0){
                $receive_coupon_id .= $v['id'].',';
            }
        }
        db('order')->where('order_sn',$order_sn)->update(['receive_coupon_id'=>$receive_coupon_id]);        //更新可以领取的优惠券id

        cookie('user_cart',$cart,15552000);     //更新购物车信息

        return ['code'=>1,'order_id'=>$order_id,'order_sn'=>$order_sn,'final_amount'=>$final_amount];
    }


    /**
     * @Author  lingyun
     * @Desc    计算运费
     * @Param   $address    收货地址
     */
    public function count_delivery_fee($address=''){
        $root = request()->domain();
        $config_arr = config('dada');
        $config_arr['url'] = "http://newopen.imdada.cn/api/order/queryDeliverFee";          //订单详情查询
        $dada_obj = new DadaOpenapi($config_arr);
        $data_arr['origin_id'] = build_order_no().cookie('store_id');
        $store = db('store')->alias('a')->join('ys_city b','a.city_code=b.code','LEFT')->where('a.id',cookie('store_id'))->field('a.*,b.dada_code')->find();            //门店信息
        $data_arr['shop_no'] = $store['dada'];           //门店编号
        $data_arr['city_code'] = $store['dada_code'];           //门店编号
        $data_arr['cargo_price'] = 0.01;           //订单金额
        $data_arr['is_prepay'] = 0;           //是否需要垫付，0否
        $data_arr['receiver_name'] = '一朵';           //是否需要垫付，0否
        $data_arr['receiver_address'] = $address;           //收货地址
        $data_arr['callback'] = $root.'/index.php/index/dada/count_delivery_fee';           //是否需要垫付，0否
        $data_arr['receiver_phone'] = '18757685769';           //是否需要垫付，0否
        $fee_info = $dada_obj->pre_count_delevety_fee($data_arr);          //与计算订单运费
        $result = json_decode($fee_info,true);
        if(empty($result)){
            return ['code'>0,'msg'=>'地址填写错误或不在配送范围，请检查并核实'];
        }else if($result['status'] =='fail' && $result['code'] != 0){
            return ['code'>0,'msg'=>'地址填写错误或不在配送范围，请检查并核实'];
//           $this->error('地址填写错误或不在配送范围，请检查并核实','');
        }

        $price = $this->getDeliveryFee($result['result']['distance']);

        return ['code'=>1,'msg'=>$price['msg']];

    }

    /**
     * @Author  lingyun
     * @Desc    计算运费
     * @param $distance
     * @return array
     */
    private function getDeliveryFee($distance){
        $distance = $distance/2/500;
        //查询运费信息
        $data = Db::name('delivery_fee')->where('is_deleted',0)->order('distance asc')->select();
        foreach($data as $k => $v){
            if($distance < $v['distance']){
                return ['code'=>1,'msg'=>$v['price']];
                break;
            }
        }
        $val = end($data);
        return ['code'=>1,'msg'=>$val['price']];
    }


    /**
     * @Author   lingyun
     * @Desc     根据订单的金额获取会员的优惠券  --  立即购买
     * @Desc     门店的关注券 -- 门店的优惠券
     * @Param    $total_amount -- 门店的优惠券
     * @Param    $cate_id-- 门店的优惠券
     */
    public function get_coupon_list($total_amount,$cate_id){
        $request = request();
//        if($request->isPost()){
//
//        }else{
        $uid = session('_user_uid_.uid');        //会员id
        $store_id = cookie('store_id');         //门店id
        $post = input('param.');                 //代金券金额
//            if(empty($store_id)){
//                $this->error('请选择门店',url('Changestore/index'));
//            }
        //门店普通优惠券
        //商品优惠券，1关注券 ， 2现金券
        $time = time();         //当前的时间
        $where_coupon_0 = [
            'a.store_id'=>$store_id,
            'a.uid'=>$uid,
            'a.is_used'=>0,
            'a.type'=>['neq','2'],
            'a.morethan'=>['elt',$total_amount],
            'a.use_start_time'=>['lt',$time],
            'a.use_end_time'=>['gt',$time],
            'a.cat_id'=>['in','0,'.$cate_id],     //优惠券的类型
            'a.status'=>1
        ];
//            halt($where_coupon_0);
        //普通优惠券 -- 关注券列表
        $coupon = db('user_ycard')->alias('a')->join('ys_store_coupon b','a.coupon_id=b.id','LEFT')->field('a.*,b.img')->where($where_coupon_0)->select();
//            if(!empty($coupon)){
//                foreach($coupon as $k => $v){
//                    $coupon[$k]['reduce'] = (int)$v['reduce'];
//                }
//            }

//            halt($coupon);
        return $coupon;

//            $this->assign('coupon',$coupon);
//
//            return $this->fetch('coupon_list');
//        }
    }

    /**
     * @Author  lingyun
     * @Desc    根据订单的金额获取会员的代金券
     * @Param   $cate_id 商品分类
     */
    public function get_cash_coupon($cate_id){
        $uid = session('_user_uid_.uid');        //会员id
        $store_id = session('store_id');        //门店id
        $post = input('param.');
        $time = time();         //当前时间
        $where = [
            'a.uid'=>$uid,
            'a.store_id'=>$store_id,
            'a.is_used'=>0,
            'a.type'=>2,
            'a.cat_id'=>['in','0,'.$cate_id],
            'a.status'=>1,
//            'a.morethan'=>['egt',$post['total_amount']],
            'a.use_start_time'=>['lt',$time],
            'a.use_end_time'=>['gt',$time],
        ];
//halt($where);
        //代金券列表
        $coupon = db('user_ycard')->alias('a')->join('ys_store_coupon b','a.coupon_id=b.id','LEFT')->where($where)->field('a.*,b.img')->select();
//        $this->assign('coupon',$coupon);
//        return $this->fetch('cash_coupon');
        return $coupon;
    }

}